# -*- coding: utf-8 -*-
from openerp.osv import fields
from openerp.osv import osv
from openerp import SUPERUSER_ID


class pick_report_wizard(osv.osv_memory):
    _name = 'pick.report.wizard'
    _columns = {
        'period': fields.many2one('account.period', string='要查看的期间'),
    }

    def create_period_pick_report(self, cr, uid, ids, context=None):
        # 统计stock.move中的产品×（入库、和出库）的数量，及价格的统计。
        pick_report = self.browse(cr, uid, ids, context=context)
        pick_period_history_none_obj = self.pool.get('pick.period.history')
        pick_period_history_line_none_obj = self.pool.get(
            'pick.period.history.line')
        old_pick_period_id = pick_period_history_none_obj.search(
            cr, uid, [('period', '=', pick_report.period.name)], context=context)
        # 如果存在已有的记录要进行删除。通过期间作为标识
        if old_pick_period_id:
            pick_period_history_none_obj.unlink(
                cr, uid, old_pick_period_id, context=context)
            pick_period_history_line_none_ids = pick_period_history_line_none_obj.search(
                cr, uid, [('period', '=', pick_report.period.name)], context=context)
            pick_period_history_line_none_obj.unlink(
                cr, uid, pick_period_history_line_none_ids, context=context)

        pick_period_history_id = pick_period_history_none_obj.create(
            cr, uid, {'period': pick_report.period.name}, context=context)
        move_obj_id = self.pool.get('stock.move').search(
            cr, uid, [('state', '=', 'done'), ('date', '>=', pick_report.period.date_start),
                      ('date', '<=', pick_report.period.date_stop), ('picking_id', '!=', False)], context=context)
        out_going = {}
        in_coming = {}
        # 统计出来的产品的数量金额，产品id暂存在 out_going 、in_coming两个字典中 {产品id：[产品数量，产品金额]}
        for move_obj in self.pool.get('stock.move').browse(cr, uid, move_obj_id, context=context):
            all_price = 0
            for quant_obj in move_obj.quant_ids:
                all_price += quant_obj.qty * quant_obj.cost
            if move_obj.location_dest_id.usage == 'internal' and move_obj.location_id.usage not in ('internal', 'transit'):
                if in_coming.get(move_obj.product_id.id):
                    in_coming_list = in_coming.get(move_obj.product_id.id)
                    in_coming.update({move_obj.product_id.id: [in_coming_list[0]
                                                               + move_obj.product_uom_qty, in_coming_list[1] + all_price]})
                else:
                    in_coming.update(
                        {move_obj.product_id.id: [move_obj.product_uom_qty, all_price]})
            if move_obj.location_id.usage == 'internal' and move_obj.location_dest_id.usage not in ('internal', 'transit'):
                if out_going.get(move_obj.product_id.id):
                    # out_going.update(
                    #     {move_obj.product_id.id: [0, 0]})
                    out_going.update({move_obj.product_id.id: [out_going[move_obj.product_id.id][0]
                                                               + move_obj.product_uom_qty,
                                                               out_going[move_obj.product_id.id][1] + all_price]})
                else:
                    out_going.update({move_obj.product_id.id: [move_obj.product_uom_qty, all_price]})
        pick_period_history_line_list = []
        in_coming_amount, out_going_amount = 0, 0
        # 以下程序 是将从stock.move中取出来的产品信息，新建月库存期间产看记录
        for prodcut_id in out_going.keys():
            vals = {}
            out_going_list = out_going.get(prodcut_id)
            vals.update({'product_id': prodcut_id, 'out_going_qty': out_going_list[0], 'out_going_aggregate_amount': out_going_list[1],
                         'in_coming_qty': (in_coming.get(prodcut_id))[0] if in_coming.get(prodcut_id) else 0,
                         'in_coming_aggregate_amount':  (in_coming.get(prodcut_id))[1] if in_coming.get(prodcut_id) else 0,
                         'period_history_id': pick_period_history_id,
                         'period': pick_report.period.name})
            out_going_amount += out_going_list[1]
            in_coming_amount += (in_coming.get(prodcut_id)
                                 )[1] if in_coming.get(prodcut_id) else 0
            pick_period_history_line_list.append(pick_period_history_line_none_obj.create(
                cr, uid, vals, context=context))
        # 因为出入库的产品可能存在差异，也就是 in_coming 和 out_going 中的数值差别，为了统计到所有的信息
        # 。所以要进行一步差集的操作
        for product_ids_incoming in list(set(in_coming.keys()) - set(out_going.keys())):
            vals = {}
            in_coming_amount += (in_coming.get(product_ids_incoming))[1]
            vals.update({'product_id': product_ids_incoming,
                         'in_coming_qty': (in_coming.get(product_ids_incoming))[0],
                         'in_coming_aggregate_amount':  (in_coming.get(product_ids_incoming))[1],
                         'period_history_id': pick_period_history_id,
                         'period': pick_report.period.name})
            pick_period_history_line_list.append(pick_period_history_line_none_obj.create(
                cr, uid, vals, context=context))
        pick_period_history_none_obj.write(cr, uid, pick_period_history_id, {
                                           'in_coming_amount': in_coming_amount, 'out_going_amount': out_going_amount}, context=context)
        # 生成库存期间记录后 通过action的方式 返回，可以直接查看到。这个地方有一点小问题，return {} 的方式填写参数 的形式进行
        # 就会出问题 返回结果为空不知为啥。需要进一步试验，尝试。
        mod_obj = self.pool.get('ir.model.data')
        act_obj = self.pool.get('ir.actions.act_window')
        result = mod_obj.get_object_reference(
            cr, uid, 'dftg_ext', 'dftg_pick_period_history_action')
        id = result and result[1] or False
        result = act_obj.read(cr, uid, [id], context=context)[0]
        res = mod_obj.get_object_reference(
            cr, uid, 'dftg_ext', 'dftg_pick_period_history_form')
        result['views'] = [(res and res[1] or False, 'form')]
        result['res_id'] = pick_period_history_id
        return result


class pick_period_history(osv.osv):
    _name = 'pick.period.history'
    _rec_name = 'period'
    _order = 'period_id DESC'

    def _get_name_period_id(self, cr, uid, ids, name, args, context=None):
        res = {}
        period_obj = self.pool.get('account.period')
        for history in self.browse(cr, uid, ids, context=context):
            period_id = period_obj.search(cr, uid, [('name', '=', history.period)], context=context)
            period_id = period_id and period_id[0]
            res[history.id] = period_id
        return res

    def unlink(self, cr, uid, ids, context=None):
        for pick_period in self.browse(cr, uid, ids, context=context):
            if pick_period.account_move_id:
                raise osv.except_osv(u'错误',  u'请先删除收发汇总表对应的分录')
        return super(pick_period_history, self).unlink(cr, uid, ids, context=context)

    _columns = {
        'product_period_lines': fields.one2many('pick.period.history.line', "period_history_id", string='产品月仓库统计明细'),
        'period': fields.char(u'期间'),
        'period_id': fields.function(_get_name_period_id, type='many2one', relation='account.period', store=True,string='期间'),
        'account_move_id': fields.many2one('account.move', u'会计分录'),
        'in_coming_amount': fields.float(u'入库金额'),
        'out_going_amount': fields.float(u'出库金额'),
    }


class pick_period_history_line(osv.osv):
    _name = 'pick.period.history.line'
    _columns = {
        'product_id': fields.many2one('product.product', string='产品'),
        'product_name': fields.related('product_id', 'name', tyep='string', string='产品名称'),
        'categ_id': fields.related('product_id', 'categ_id', type='many2one', relation='product.category', string='产品分类', stroe=True),
        'in_coming_qty': fields.float(u'本月入库数量'),
        'out_going_qty': fields.float(u'本月出库数量'),
        'out_going_aggregate_amount': fields.float(u'本月出库金额'),
        'in_coming_aggregate_amount': fields.float(u'本月入库金额'),
        'period': fields.char(u'期间'),
        'period_history_id': fields.many2one('pick.period.history', string='主记录'),
    }


class create_account_move_wizard(osv.osv_memory):
    _name = 'create.account.move.wizard'
    _columns = {
        'message': fields.text(u'信息')
    }

    def _set_default_message(self, cr, uid, context=None):
        history_obj = self.pool.get('pick.period.history')
        period_name_list = []
        for history in history_obj.browse(cr, uid, context.get('active_ids'), context=context):
            if history.account_move_id:
                continue
            period_name_list.append(history.period)
        return '确认生成期间为：%s 的月仓库收发汇总会计分录' % '、'.join(period_name_list)

    _defaults = {
        'message': _set_default_message,
    }

    def create_period_pick_account_move(self, cr, uid, ids, context=None):
        history_obj = self.pool.get('pick.period.history')
        move_obj = self.pool.get('account.move')
        account_obj = self.pool.get('account.account')
        journal_obj = self.pool.get('account.journal')
        goods_cost_id = account_obj.search(cr, uid, [('code', '=', '6401')], context=context)
        goods_account_id = account_obj.search(cr, uid, [('code', '=', '1407')], context=context)
        journal_id = journal_obj.search(cr, uid, [('name', '=', '采购分录')], context=context)
        goods_cost_id = goods_cost_id and goods_cost_id[0]
        goods_account_id = goods_account_id and goods_account_id[0]
        journal_id = journal_id and journal_id[0]
        move_ids = []
        for history in history_obj.browse(cr, uid, context.get('active_ids'), context=context):
            if history.account_move_id:
                continue
            vals = {
                'journal_id': journal_id,
                'period_id': history.period_id.id,
                'ref': '%s 出库结转' % history.period,
                'line_id': [(0, 0, {'name': '%s 出库结转' % history.period, 'account_id': goods_cost_id, 'debit': history.out_going_amount}),
                            (0, 0, {'name': '%s 出库结转' % history.period, 'account_id': goods_account_id, 'credit': history.out_going_amount})]
            }
            move_id = move_obj.create(cr, uid, vals, context=context)
            history.write({'account_move_id': move_id})
            move_ids.append(move_id)
        mod_obj = self.pool.get('ir.model.data')
        act_obj = self.pool.get('ir.actions.act_window')
        result = mod_obj.get_object_reference(
            cr, uid, 'account', 'action_move_journal_line')
        id = result and result[1] or False
        result = act_obj.read(cr, uid, [id], context=context)[0]
        if len(move_ids) > 1:
            result[
                'domain'] = "[('id','in',[" + ','.join(map(str, move_ids)) + "])]"
        else:
            res = mod_obj.get_object_reference(
                cr, uid, 'account', 'view_move_form')
            result['views'] = [(res and res[1] or False, 'form')]
            result['res_id'] = move_ids and move_ids[0] or False
        return result
        return ''
